import { login, getUserInfo, getUserDatailById } from '@/api/user'

import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 修改token
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  // 请求接口
  actions: {
    async login(store, from) {
      const res = await login(from)
      store.commit('setToken', res.data)
      return res
    },
    async fetchUserInfo(store) {
      const res = await getUserInfo()
      const res1 = await getUserDatailById(res.data.userId)
      store.commit('setUserInfo', { ...res.data, ...res1.data })
      return res
    }
  }
}
